package com.yanxu;

import com.yanxu.domain.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/7/27-2025
 * @Description: 这里用一句话描述这个类的作用
 */
public class Api_16_SlidingWindowReduceSample {
    public static void main(String[] args) throws Exception {
        //定义执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //source 源
        DataStreamSource<Event> dataStreamSource = env.addSource(new CustomSource());
        //定义水位线、时间戳
        SingleOutputStreamOperator<Event> operator = dataStreamSource.assignTimestampsAndWatermarks(
                WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ZERO)
                        .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                            @Override
                            public long extractTimestamp(Event event, long recordTimestamp) {
                                return event.getTimestamp();
                            }
                        })
        );

        // map 进行转换算子
        SingleOutputStreamOperator<Tuple2<String, Long>> mapOperator = operator.map(new MapFunction<Event, Tuple2<String, Long>>() {
            @Override
            public Tuple2<String, Long> map(Event event) throws Exception {
                return Tuple2.of(event.getName(), 1L);
            }
        });
        // keyBy 进行分区
        KeyedStream<Tuple2<String, Long>, String> keyedStream= mapOperator.keyBy(r -> r.f0);
        // 使用window 时间窗口进行处理
        keyedStream
                // 使用 sliding 滑动时间窗口进行处理
                .window(SlidingEventTimeWindows.of(Time.seconds(5),Time.seconds(1)))
                //.sum("f1")
                // 规约聚合进行处理
                .reduce(new ReduceFunction<Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> reduce(Tuple2<String, Long> value1, Tuple2<String, Long> value2) throws Exception {
                        return Tuple2.of(value1.f0, value1.f1 + value2.f1);
                    }
                })
                // print 进行打印
                .print("sliding 滑动窗口处理 >>>>> ");


        // flink 启动
        env.execute();

    }
}